package cn.com.member.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.api.entity.ApiSmslog;
import cn.com.api.entity.ApiT_member;
import cn.com.api.entity.ApiT_member_entrepreneur;
import cn.com.api.entity.ApiTmember;
import cn.com.api.service.ApiAddressService;
import cn.com.api.service.ApiMemberService;
import cn.com.api.service.ApiSmslogService;
import cn.com.api.service.ApiT_memberService;
import cn.com.api.service.ApiT_member_entrepreneurService;
import cn.com.util.CipherUtil;
import cn.com.util.Code;
import cn.com.util.JsonUtil;
import cn.com.util.ReturnObj;
import cn.com.util.Util;
import cn.com.util.Utils;



@Controller
@RequestMapping
public class MemberMainController {

	private static Logger logger = Logger.getLogger(MemberMainController.class);

	@Autowired
	private ApiMemberService apiMemberService;
	@Autowired
	private ApiT_memberService apiT_memberService;
	@Autowired
	private ApiSmslogService apiSmslogService;
	@Autowired
	private ApiAddressService addressService;
	@Autowired
	private ApiT_member_entrepreneurService apiT_member_entrepreneurService;
	
	@RequestMapping("index")
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
		//
		Map<String, Object> ret_map = new HashMap<String, Object>();
		ModelAndView mv = null;

	try {
			ApiTmember member = (ApiTmember) request.getSession().getAttribute(
					"webuser");// 登陆用户
			ApiT_member apiT_member = apiT_memberService.findT_memberById(member.getCid());
			ret_map.put("member", apiT_member);	
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		mv = new ModelAndView("/index", ret_map);
		return mv;
	}

	@RequestMapping("login")
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> ret_map = new HashMap<String, Object>();
		ModelAndView mv = null;

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		try {
			if (username != null && password != null) {						
				ApiTmember member = new ApiTmember();
				
				member.setCuserid(username);
				member.setCmob(username);
				member.setCpass(CipherUtil.generatePassword(password));
				
				ApiTmember returnMember = this.apiMemberService.weblogin(member);
				if (returnMember != null) {
					if(returnMember.getVerify_entrepreneur()==1){
						request.getSession().setAttribute("webuser", returnMember);
						request.getSession().setAttribute("password", password);
						mv = new ModelAndView("redirect:/index");
					}else{
						ret_map.put("error_info", "您还不是认证的企业主");
						ret_map.put("username", username);
						mv = new ModelAndView("/login", ret_map);
					}
					
				} else {
					ret_map.put("error_info", "用户名或密码错误");
					ret_map.put("username", username);
					mv = new ModelAndView("/login", ret_map);
				}
			}else{
				mv = new ModelAndView("/login", ret_map);
			}			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	    //
		return mv;
	}
	
	// 退出系统
	@RequestMapping("logout")
	public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) {
		//
		Map<String, Object> ret_map = new HashMap<String, Object>();
		ModelAndView mv = null;
		try {
			request.getSession().removeAttribute("webuser");
			request.getSession().removeAttribute("car");
			request.getSession().removeAttribute("products");
			ret_map.put("method", "login");
		} catch (Exception e) {
			e.printStackTrace();
		}
		mv = new ModelAndView("/login", ret_map);
		return mv;
	}	
	
	/**
	 * 跳转用户端忘记密码界面
	 * */
	@RequestMapping(value = "forget_pwd")
	public ModelAndView forget_pwd(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//
	/*	String cTel = request.getParameter("c_mob");
		ApiTmember member = apiMemberService.findMemberByCuserid(cTel);
		ApiSmslog apiSmslog = new ApiSmslog();
		apiSmslog.setcTel(member.getCmob());*/
		Map<String, Object> ret_map = new HashMap<String, Object>();
		ModelAndView mv = null;
		mv = new ModelAndView("/member/forget_pwd", ret_map);
		return mv;
	}
	
	/**
	 * 用户忘记密码，重设密码
	 * */
	@RequestMapping(value = "forget_pwd_reset")
	public void forgetpwd_reset(HttpServletRequest request, HttpServletResponse response) throws Exception {
	
		String cTel = request.getParameter("c_mob");
		String cPass = request.getParameter("cPass");
		String code = request.getParameter("code"); // 验证码
		
		ReturnObj baseObj = new ReturnObj();
			try {
				// 忘记密码接口，先查询用户，更新用户密码信息，更新验证码信息 返回用户信息
				ApiTmember member = apiMemberService.findMemberByCuserid(cTel);
				member.setCpass(CipherUtil.generatePassword(cPass));// 设置新密码
				Date now = new Date();
				SimpleDateFormat dateFormat = new SimpleDateFormat(
						"yyyy/MM/dd HH:mm:ss");
				member.setClogdate(dateFormat.format(now));// 不需要再重新登录
				ApiSmslog apiSmslog = new ApiSmslog();
				apiSmslog.setcTel(member.getCmob());
				apiSmslog.setCode(code);
				// 注册
				// 校验验证码是否正确
				if (apiSmslogService.checkCode(apiSmslog)) {
					apiMemberService.forgetCPass(member, apiSmslog);
					baseObj.handleSuccess();
				} else {
					baseObj.setCodeAndInfo(Code.EXCEPTION_CODE, "验证码不匹配，请重新填写！");
				}	

			} catch (Exception e) {
				e.printStackTrace();
				logger.error(Util.getStackTraceAsString(e));
				baseObj.setCodeAndInfo(Code.EXCEPTION_CODE, "系统异常！");
			}
			//
			JsonUtil.printJson(response, JsonUtil.object2json(baseObj));
	}
	
	/**
	 * 密码重置修改
	 * **/
	@RequestMapping("pwd-reset")
	public ModelAndView reset_pwd(HttpServletRequest request,
			HttpServletResponse response) {
		//
		Map<String, Object> ret_map = new HashMap<String, Object>();
		ModelAndView mv = null;
		try {
			ApiTmember member = (ApiTmember) request.getSession().getAttribute("webuser");// 登陆用户
			ret_map.put("member", member);

		} catch (Exception e) {
			e.printStackTrace();
		}
		//
		mv = new ModelAndView("/member/password", ret_map);
		return mv;
	}

	@RequestMapping("editpwd")
	public void editpwd(HttpServletRequest request, HttpServletResponse response) {
	ReturnObj baseObj = new ReturnObj();
		try {
			String oldpwd = request.getParameter("oldpwd");
			String newpwd = request.getParameter("newpwd");
			ApiTmember member = (ApiTmember) request.getSession().getAttribute(
					"webuser");// 登陆用户
			ApiT_member apiT_member = apiT_memberService
					.findT_memberById(member.getCid());
			if (apiT_member.getC_pass().equals(
					CipherUtil.generatePassword(oldpwd))) {// 原密码相等
				apiT_member.setC_pass(CipherUtil.generatePassword(newpwd));
				apiT_memberService.updateT_member(apiT_member);
				baseObj.handleSuccess();
			} else {
				baseObj.setCodeAndInfo(Utils.RESULT_RC_EXCEPTION, "原密码不正确");
			}
		} catch (Exception e) {
			e.printStackTrace();
			baseObj.handleException(e);
		}
		JsonUtil.printJson(response, JsonUtil.object2json(baseObj));
	}
	
	/* @author 田明星
	 * 忘记密码输入验证码后重新设置新密码
	 * @param request
	 * @param response
	 */
	@RequestMapping("user_forgetpwd_reset")
	public void user_forgetpwd_reset(HttpServletRequest request, HttpServletResponse response) {
	ReturnObj baseObj = new ReturnObj();
		try {
			apiMemberService.updatePwdByMobile(request.getParameter("c_mob"),CipherUtil.generatePassword(request.getParameter("renewpwd")));
		} catch (Exception e) {
			e.printStackTrace();
			baseObj.handleException(e);
		}
		JsonUtil.printJson(response, JsonUtil.object2json(baseObj));
	}
	
	
	
	/**
	 * 用户信息
	 * **/
	@RequestMapping("member-info")
	public ModelAndView member_info(HttpServletRequest request,
			HttpServletResponse response) {
		//
		Map<String, Object> ret_map = new HashMap<String, Object>();
		ModelAndView mv = null;
		try {
			ApiTmember member = (ApiTmember) request.getSession().getAttribute(
					"webuser");// 登陆用户
			ApiT_member apiT_member = apiT_memberService.findT_memberById(member.getCid());
			ret_map.put("member", apiT_member);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//
		mv = new ModelAndView("/member/userinfo", ret_map);
		return mv;
	}

	
	// 修改用户信息
	@RequestMapping(value = "/member_update")
	public void member_update(@ModelAttribute ApiTmember apiTmember,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> ret_map = new HashMap<String, Object>();
		try {
			ApiTmember member = (ApiTmember) request.getSession().getAttribute("webuser");// 登陆用户
			ApiT_member apiT_member = apiT_memberService.findT_memberById(member.getCid());
			apiT_member.setC_nick(apiTmember.getCnick());
			apiT_member.setC_tname(apiTmember.getCtname());
			apiT_member.setC_mob(apiTmember.getCmob());
			apiT_member.setC_mail(apiTmember.getCmail());
			apiT_member.setC_sex(apiTmember.getCsex());
			apiT_member.setC_avatar(apiTmember.getCavatar());
			apiT_member.setC_birthday(apiTmember.getCbirthday());
			apiT_member.setC_address(apiTmember.getCaddress());
			apiT_member.setC_area(apiTmember.getCarea());
			apiT_member.setC_city(apiTmember.getCcity());
			apiT_memberService.updateT_member(apiT_member);
			//
			ret_map.put("member", apiT_member);
			ret_map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			ret_map.put(Utils.MESSAGE, "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);			
			ret_map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			ret_map.put(Utils.MESSAGE, "系统异常");
		}
		//
		JsonUtil.printJson(response, JsonUtil.object2json(ret_map));
	}

	/**
	 * 用户忘记密码-发送验证码
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "/forget")
	public void forget(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String cMob = request.getParameter("cMob");
		String code = request.getParameter("code");
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (cMob != null && !"".equals(cMob.trim())) {
				// 判断手机号是否已注册，未注册提示用户新账号
				ApiTmember member = apiMemberService.checkMemberExist(cMob);
				if (member != null) {// 注册过
					String random = apiMemberService.sendIdentifyCode(member.getCmob(), 1);// 1-用户忘记密码
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "successs");
					Map<String, Object> datas = new HashMap<String, Object>();
					datas.put("code", random);
					map.put("datas", datas);
		
			/*		member.setCmob(cMob);// 手机号
					ApiSmslog apiSmslog = new ApiSmslog();
					apiSmslog.setcTel(cMob);
					apiSmslog.setCode(code);
					// 校验验证码是否正确
					if (apiSmslogService.checkCode(apiSmslog)) {
						// 注册
						ApiTmember Nmember = apiMemberService.regist( code, member, apiSmslog);
						map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
						map.put(Utils.MESSAGE, "success");
						map.put("datas", Nmember);
					} else {
						map.put(Utils.RESULT, "0002");
						map.put(Utils.MESSAGE, "验证码不匹配，请重新填写！");
					}*/
				} else {
					map.put(Utils.RESULT, "0003");
					map.put(Utils.MESSAGE, "手机号未注册，请注册！");
				}

			} else {
				map.put(Utils.RESULT, "0008");
				map.put(Utils.MESSAGE, "手机号不能为空！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		// response.setCharacterEncoding("UTF-8");
		// PrintWriter out = response.getWriter();
		// out.write(JsonUtil.object2json(map));
		// out.close();
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	@RequestMapping("portal")
	public ModelAndView portal(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("/index_v1");

		try {
			ApiTmember member = (ApiTmember) request.getSession().getAttribute("webuser");// 登陆用户
			
			ApiT_member_entrepreneur apiT_member_entrepreneur = apiT_member_entrepreneurService.getEntrepreneurIdByUserId(member.getCid());
			mv.addObject("member_entrepreneurs", apiT_member_entrepreneur);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return mv;
	}
	
	/**
	 * 根据手机号码获得数据库里的code验证码
	 * @author 田明星
	 * @param mob
	 * @return
	 */
	@RequestMapping(value = "/getCodeBymobile")
	public @ResponseBody String getCodeBymobile(String mob){
		String code="";
		try {
		code =	apiSmslogService.getCodeBymob(mob);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return code;

	}
	/**
	 * 锁屏
	 * **/
	@RequestMapping("lockscreen")
	public  ModelAndView lockscreen(HttpServletRequest request, HttpServletResponse response) {
		//
		//System.out.println(request.getParameter("mob"));
		//System.out.println(request.getParameter("password"));
		Map<String, Object> ret_map = new HashMap<String, Object>();
		ModelAndView mv = null;
		try {
			ret_map.put("mob", request.getParameter("mob"));
			ret_map.put("password", request.getParameter("password"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		mv = new ModelAndView("/main/lockscreen", ret_map);
		return mv;
	}	
	
}